Page({
  data: {
    // idcardFrontUrl: '/static/images/avatar_1.jpg',
    // idcardBackUrl: '/static/images/avatar_2.jpg',
    idcardFrontUrl: '',
    idcardBackUrl: '',
    point: '',
    building: '',
    room: '',
    name: '',
    gender: '0',
    mobile: ''
  },
  // onLoad(options){
  onLoad({
    point,
    room,
    building,
    id
  }) {
    this.init(point, room, building, id)
  },
  async init(point, room, building, id) {
    if (id) {
      wx.setNavigationBarTitle({
        title:'编辑房屋信息'
      })
      const res = await wx.http.get(`/room/${id}`)
      this.setData(Object.assign({}, {...res.data}, {gender: res.data.gender.toString()}))

    } else {
      this.setData({
        point,
        room,
        building
      })
    }
  },
  updateImg(e) {
    const that = this
    // 上传图片的api
    wx.chooseMedia({
      count: 9,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        wx.uploadFile({
          url: 'https://live-api.itheima.net/upload',
          filePath: res.tempFiles[0].tempFilePath,
          name: 'file',
          header: {
            Authorization: getApp().token
          },
          success(res) {
            const tmp = JSON.parse(res.data)
            that.setData({
              // idcardFrontUrl: tmp.data?.url
              [e.currentTarget.dataset.type]: tmp.data?.url
            })
          }
        })
      }
    })
  },
  async goList() {
    if (!this.validateName() || !this.validateMobile() || !this.validateImg()) return
    const  data =  {
      point: this.data.point,
      building: this.data.building,
      room: this.data.room,
      name: this.data.name,
      gender: this.data.gender,
      mobile: this.data.mobile,
      idcardFrontUrl: this.data.idcardFrontUrl,
      idcardBackUrl: this.data.idcardBackUrl
    }
    const postData = this.data.id ? Object.assign(data,{id:this.data.id}) : data
    const res = await wx.http({
      url: '/room',
      method: 'POST',
      data: postData
    })
    if (res.code !== 10000) {
      wx.utils.toast('新增房屋失败')
      return
    }
    wx.navigateBack({
      delta: this.data.id? 2: 4
    })
  },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark?.type
    this.setData({
      [type]: ''
    })
  },

  // 下面是三个字段的校验函数，要自己写
  validateName() {
    // 姓名必须是2-5个汉字
    const pattern = /^[\u4e00-\u9fa5]{2,5}$/
    if (!pattern.test(this.data.name)) {
      wx.utils.toast('姓名校验失败')
      return false
    }
    return true
  },
  validateMobile() {
    // 姓名必须是2-5个汉字
    const pattern = /^1[356789]\d{9}$/
    if (!pattern.test(this.data.mobile)) {
      wx.utils.toast('手机号校验失败')
      return false
    }
    return true
  },
  validateImg() {
    if (!this.data.idcardFrontUrl || !this.data.idcardBackUrl) {
      wx.utils.toast('身份证正反面照片必传')
      return false
    }
    return true
  }
})